package com.github.catvod.spider;

import android.text.TextUtils;

import com.github.catvod.bean.Class;
import com.github.catvod.bean.Result;
import com.github.catvod.bean.Vod;
import com.github.catvod.crawler.Spider;
import com.github.catvod.net.OkHttp;
import com.github.catvod.utils.Json;
import com.github.catvod.utils.ProxyVideo;
import com.github.catvod.utils.Util;

import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * 139影视:https://www.139ys.com/
 */
public class One39 extends Spider {
    private String siteUrl = "https://www.139ys.com";
    private String categoryUrl=siteUrl+"/vodtype/";
    private String api="https://api.ikunyy.com/";
    private String searchUrl=siteUrl+"/vodsearch/-------------.html";


    private HashMap<String, String> getHeaders() {
        HashMap<String, String> headers = new HashMap<>();
        headers.put("User-Agent", Util.CHROME);
        return headers;
    }
    @Override
    public String homeContent(boolean filter) throws Exception {
        List<Vod> list = new ArrayList<>();
        List<com.github.catvod.bean.Class> classes = new ArrayList<>();
        String[] typeIdList = {"/", "dianying", "lianxuju", "zongyi", "dongman", "zhibo"};
        String[] typeNameList = {"首页","电影", "连续剧", "综艺", "动漫", "直播"};
        for (int i = 0; i < typeNameList.length; i++) {
            classes.add(new Class(typeIdList[i], typeNameList[i]));
        }
        return Result.string(classes, list);
    }

    @Override
    public String categoryContent(String tid, String pg, boolean filter, HashMap<String, String> extend) throws Exception {
        if (tid.equals("/")){
            // 首页
            Document doc = Jsoup.parse(OkHttp.string(siteUrl, getHeaders()));
            List<Vod> list = parseVodListFromDoc(doc);
            return Result.string(1, 1, 20, list.size(), list);
        }
        String url = categoryUrl + tid.concat("-").concat(pg).concat(".html");
        Document doc = Jsoup.parse(OkHttp.string(url, getHeaders()));
        List<Vod> list = parseVodListFromDoc(doc);
        return Result.string(Integer.parseInt(pg),Integer.parseInt(pg)+1,20,list.size(),list);
    }

    @Override
    public String detailContent(List<String> ids) throws Exception {
        Document doc = Jsoup.parse(OkHttp.string(siteUrl+ids.get(0), getHeaders()));
        String name = doc.select("h1.title").text();
        String pic = doc.select("a.picture > img.lazyload").attr("data-original");
        Elements detail = doc.select("div.myui-content__detail > p.data");
        String text = detail.get(0).text();
        String actor = detail.get(1).text().replace("主演：","");
        String daoyan = detail.get(2).text().replace("导演：","");
        String content = detail.get(3).text().replace("简介：","");
        Elements fromLi = doc.select("div.myui-panel__head > ul.nav-tabs > li");
        List<String> fromName= new ArrayList<>();
        for (Element from : fromLi) {
            fromName.add(from.text());
        }
        List<String> playUrl = new ArrayList<>();
        Elements playUrlList = doc.select("div.tab-content > div.tab-pane");
        for (Element play : playUrlList) {
            Elements playlink = play.select("ul.myui-content__list > li");
            StringBuilder stringBuilder = new StringBuilder();
            for (Element link : playlink) {
                String playName = link.select("a").text();
                String linkUrl =  link.select("a").attr("href");
                // 如果是最后一个元素不加#号
                if (playlink.get(playlink.size() - 1).equals(link)){
                    stringBuilder.append(playName).append("$").append(linkUrl);
                }else {
                    stringBuilder.append(playName).append("$").append(linkUrl).append("#");
                }
            }
            playUrl.add(stringBuilder.toString());
        }
        Vod vod = new Vod();
        vod.setVodId(ids.get(0));
        vod.setVodPic(pic);
        vod.setVodName(name);
        vod.setVodRemarks(text);
        vod.setVodPlayFrom(TextUtils.join("$$$",fromName));
        vod.setVodPlayUrl(TextUtils.join("$$$",playUrl));
        vod.setVodActor(actor);
        vod.setVodDirector(daoyan);
        vod.setVodContent(content);
        return Result.string(vod);
    }

    @Override
    public String playerContent(String flag, String id, List<String> vipFlags) throws Exception {
        String playerUrl=siteUrl.concat(id);
        String html = OkHttp.string(playerUrl, getHeaders());
        String player_info = Util.findByRegex("var player_aaaa=(.*)</script>", html, 1);
        JSONObject json = Json.parseJson(player_info);
        String m3u8 = json.getString("url");
        HashMap<String, String> params = new HashMap<>();
        params.put("url",m3u8);
        // 进行判断是否需要进行解析
        if (m3u8.contains("html")){
            return Result.get().url(m3u8).parse().header(getHeaders()).string();
        }
        String result = OkHttp.string(api, params, getHeaders());
        JSONObject jsonObject = Json.parseJson(result);
        String url = jsonObject.getString("url");
        return Result.get().url(url).header(getHeaders()).string();
    }

    @Override
    public String searchContent(String key, boolean quick) throws Exception {
        HashMap<String, String> params = new HashMap<>();
        params.put("wd",key);
        params.put("submit","");
        Document doc = Jsoup.parse(OkHttp.string(searchUrl, params, getHeaders()));
        List<Vod> list = parseVodListFromDoc(doc);
        return Result.string(list);
    }

    private List<Vod> parseVodListFromDoc(Document doc) {
        Elements items = doc.select("div.myui-vodlist__box");
        List<Vod> list = new ArrayList<>();
        if (items.isEmpty()) {
            items = doc.select("ul.myui-vodlist__media > li");
        }
        for (Element item : items) {
            String name = item.select("h4.title").text();
            String pic = item.select("a.myui-vodlist__thumb").attr("data-original");
            String id = item.select("a.myui-vodlist__thumb").attr("href");
            list.add(new Vod(id, name, pic));
        }
        return list;
    }
}
